import { useRouter } from "vue-router";
import { useKeepAliveStore } from "@/stores/keepalive";

interface CacheItem {
  name: string;
  lastAccess: number;
}

export function useDynamicKeepAlive(maxCacheSize = 5) {
  const router = useRouter();
  const store = useKeepAliveStore();
  let cachedViews = store.cachedViews;

  // 从路由中获取组件名称
  const getComponentName = (route: any) => {
    const comp = route.matched[route.matched.length - 1]?.components?.default;
    return comp?.name || (comp?.__name as string) || route.name;
  };

  // 更新缓存访问时间
  const updateCacheAccessTime = (name: string) => {
    const now = Date.now();
    const index = store.cacheRecords.findIndex(
      (item: CacheItem) => item.name === name
    );

    if (index >= 0) {
      // 创建新数组以触发响应式更新
      store.cacheRecords = store.cacheRecords.map(
        (item: CacheItem, i: number) =>
          i === index ? { ...item, lastAccess: now } : item
      );
    } else {
      store.cacheRecords.push({ name, lastAccess: now });
    }

    // 按访问时间排序 (最近访问的排在前面)
    store.cacheRecords.sort(
      (a: CacheItem, b: CacheItem) => b.lastAccess - a.lastAccess
    );
  };

  // 添加缓存
  const addCachedView = (route: any) => {
    if (!route.meta.keepAlive) return;

    const name = getComponentName(route);
    if (!name) return;

    // 如果已经在缓存中，只需更新访问时间
    if (store.cachedViews.includes(name)) {
      updateCacheAccessTime(name);
      return;
    }

    // 检查是否超过最大缓存数
    if (store.cachedViews.length >= maxCacheSize) {
      // 移除最久未访问的缓存
      const oldestCache = store.cacheRecords.pop();
      if (oldestCache) {
        store.cachedViews = store.cachedViews.filter(
          (item) => item !== oldestCache.name
        );
      }
    }

    // 添加新缓存
    store.cachedViews.push(name);
    
    updateCacheAccessTime(name);
  };

  // 清空所有缓存
  const clearAllCache = () => {
    store.cachedViews = [];
    store.cacheRecords = [];
  };

  // 移除缓存
  const removeCachedView = (route: any, routename?: string) => {
    let name: any;
    if (route) {
      name = getComponentName(route);
    } else {
      name = routename;
    }

    if (name) {
      store.cachedViews = store.cachedViews.filter((item) => item !== name);
      store.cacheRecords = store.cacheRecords.filter(
        (item) => item.name !== name
      );
    }
  };

 // 设置路由守卫
  router.beforeEach((to, from) => {
    if (from.matched.length > 0 && from.meta.keepAlive) {
      addCachedView(from);
    }
    return true;
  });

  // 监听路由变化，更新缓存访问时间
  router.afterEach((to) => {
    const name = getComponentName(to);
    if (name && cachedViews.includes(name)) {
      updateCacheAccessTime(name);
    }
  });

  return {
    addCachedView,
    removeCachedView,
    clearAllCache,
  };
}
